package server.main.config.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import server.main.config.BeanInsert.Beans.GetLoginPage;
import server.main.mapper.PermissionMapper;
import server.main.pojo.Permission;
import server.main.pojo.Role;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义FilterInvocationSecurityMetadataSource
 */
@Component
public class CustomerFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermissionMapper permissionMapper;
    private static List<Permission> allPermission = null; // 数据库中所有的资源信息
    private List<String> loginurls = null;

//    @Autowired
//    GetLoginPage getLoginPage;
    //    private String loginurl = null;
    /**
     * 获取所有的资源信息，对allPermission进行初始化
     * 在getAttributes()方法内不可直接使用permissionMapper，因为Security先于Spring加载，此时还没有注入，会报空指针异常
     * 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，并且只会被服务器执行一次,依赖注入初始化后会自动执行该方法
     */
//	@PostConstruct
//	private List<Permission> getPermission() {
//		if (allPermission == null) {
//			System.out.println("<-----PermissionMapper----->" + permissionMapper);
//			allPermission = permissionMapper.getAllpermission();
//			//需要将每个permission和role绑起来
//			for (Permission permission : allPermission) {
//				permission.setRoles(permissionMapper.getRoles(permission.getId()));
//			}
//			System.out.println("<-----allPermission----->" + JSON.toJSONString(allPermission));
//		}
//		return allPermission;
//	}

    /**
     * 通过当前请求的URL获取角色信息
     *
     * @param o(FilterInvocation) 用于获取当前请求的url
     * @return 当前请求url所需的角色
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
//        System.out.println("*****************************************************************");
//        System.out.println("----------------> CustomerFilterInvocationSecurityMetadataSource.getAttributes(Object)");
        String url = ((FilterInvocation) o).getRequestUrl();
//        System.out.println("-----url-----> " + url);
        List<Role> goalrole = new ArrayList<>();
//        System.out.println(allPermission.size());

        List<String> temp = new ArrayList<>();
        temp.add("/pages/after/main.html");
        temp.add("/pages/after/home.html");
//        if (loginurls == null) {
//            System.out.println(getLoginPage.getlogin());
//            loginurls = getLoginPage.getlogin();
//        }

        for (String loginurl : temp) {
            if (antPathMatcher.match(loginurl, url)) {
                return SecurityConfig.createList("ROLE_LOGIN");
            }
        }


        for (Permission permission : allPermission) {

//            System.out.println(permission.getPattern() + "     " + url + "             " + antPathMatcher.match(permission.getPattern(), url));
            if (antPathMatcher.match(permission.getPattern(), url)) {
//                System.out.println("添加");
                goalrole.addAll(permission.getRoles());
            }

        }
//        System.out.println("******************" + goalrole);
        if (goalrole.size() != 0) {
            String[] roleArr = new String[goalrole.size()];
            for (int i = 0; i < roleArr.length; i++) {
                roleArr[i] = goalrole.get(i).getName();
            }
            return SecurityConfig.createList(roleArr);
        }

        return SecurityConfig.createList("ROLE_LOGIN");
    }

    /**
     * 返回所有定义好的权限资源
     * Spring Security在启动时会校验相关配置是否正确，如果不需要校验，直接返回null
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
//        System.out.println("----------------> CustomerFilterInvocationSecurityMetadataSource.getAllConfigAttributes()");
        return null;
    }

    /**
     * 是否支持校验
     */
    @Override
    public boolean supports(Class<?> aClass) {
//        System.out.println("----------------> CustomerFilterInvocationSecurityMetadataSource.supports(Class<?>)");
        return true;
    }


    public void setAllPermission(List<Permission> allPermissions) {
        allPermission = allPermissions;
    }


    public List<String> getLoginurls() {
        return loginurls;
    }

    public void setLoginurls(List<String> loginurls) {
        this.loginurls = loginurls;
    }

    public List<Permission> getAllPermission() {
        return allPermission;
    }
}
